<template>
  <div>
       <!-- 面包屑导航区域 -->
   <el-breadcrumb separator-class="el-icon-arrow-right">
  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>权限管理</el-breadcrumb-item>
  <el-breadcrumb-item>角色列表</el-breadcrumb-item>
</el-breadcrumb>
    <!--卡片视图  -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddRouter">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe>
      <!-- 展开列 -->
          <el-table-column type="expand">
            <!-- 作用域插槽 -->
            <template v-slot:default="scoped" >
            <el-row v-for="(item,index) in scoped.row.children" :key="item.id"  :class="['bdbottom',index ===0?'dbttop':'','vcenter']">
              <!-- 渲染一级权限 -->
                <el-col :span="5">
                <el-tag  closable @close="removeRightById(scoped.row,item.id)" >{{item.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 渲染二级和三级权限 -->
                <el-col :span="19">
                <!-- 通过for循环嵌套渲染二级权限 -->
                  <el-row :class="[index2!==0?'dbttop':'','vcenter']" v-for="(item2,index2) in item.children" :key="item2.id" >
                    <!-- 二级权限 -->
                     <el-col :span="6" >
                      <el-tag type="success"  closable @close="removeRightById(scoped.row,item2.id)">{{item2.authName}}</el-tag>
                      <i class="el-icon-caret-right"></i>
                     </el-col>
                     <!-- 三级权限 -->
                     <el-col :span="18">
                     <!-- 角色的id和权限的id -->
                     <el-tag closable @close="removeRightById(scoped.row,item3.id)" type="success" v-for="(item3) in item2.children" :key="item3.id">{{item3.authName}}</el-tag>
                     </el-col>
                  </el-row>
                </el-col>
            </el-row>
            </template>
          </el-table-column>
           <!-- 索引列 -->
          <el-table-column type="index"></el-table-column>
          <el-table-column label="角色名称" prop="roleName"></el-table-column>
          <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
          <el-table-column label="操作" width="300px">
            <!-- 作用域插槽 -->
            <template v-slot:default = "{row}">
                  <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEidtRouter(row.id)">编辑</el-button>
                  <el-button size="mini" type="danger" icon="el-icon-delete" @click="showDeleteById(row.id)">删除</el-button>
                  <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDialog(row)">分配权限</el-button>
            </template>
          </el-table-column>
      </el-table>
    </el-card>
<!-- 添加角色 -->
    <el-dialog
  title="添加角色"
  :visible.sync="isAddRouterDialog"
  width="50%"
  @close="resetRouterFrom">
  <el-form  ref="addRouterFromRef" :rules="addRouterFromRules"  :model="addRouterFrom" label-width="80px">
  <el-form-item label="角色名称"  prop="roleName">
    <el-input v-model="addRouterFrom.roleName"></el-input>
  </el-form-item>
  <el-form-item label="角色描述"  prop="roleDesc">
    <el-input v-model="addRouterFrom.roleDesc"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="isAddRouterDialog = false">取 消</el-button>
    <el-button type="primary" @click="addRouter">确定</el-button>
  </span>
</el-dialog>
<!-- 修改角色 -->
<el-dialog
  title="修改角色"
  :visible.sync="isEidtRouterDialog"
  width="50%"
  @colse="editRouterColsed">
 <el-form ref="editRouterRef" :model="editRouterFrom" :rules="editRouterFromRules" label-width="80px">
  <el-form-item label="角色名称" prop="roleName">
    <el-input v-model="editRouterFrom.roleName"></el-input>
  </el-form-item>
  <el-form-item label="角色描述" prop="roleDesc">
    <el-input v-model="editRouterFrom.roleDesc"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="isEidtRouterDialog = false">取 消</el-button>
    <el-button type="primary" @click="editRouter">确 定</el-button>
  </span>
</el-dialog>
<!-- 分配权限 -->
<el-dialog
  title="提示"
  :visible.sync="setRightDialogVisible"
  width="50%"
  @close="setRightDialogColosed">
  <!-- 树型控件 -->
<el-tree ref="treeRef" :default-checked-keys="defKeys" default-expand-all node-key="id" show-checkbox :data="rightsList" :props="treeProps"></el-tree>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRightDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
export default {
  name: 'R-outer',
  data () {
    return {
      /* 所有角色的列表数据 */
      rolesList: [],
      /* 是否显示添加角色对话框 */
      isAddRouterDialog: false,
      /* 添加角色时的数据存储 */
      addRouterFrom: {
        roleName: '',
        roleDesc: ''
      },
      /* 标签权限校验规则 */
      addRouterFromRules: {
        roleName: [
          { required: true, message: '请填写角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请填写角色描述', trigger: 'blur' }

        ]
      },
      /* 显示修改角色对话框 */
      isEidtRouterDialog: false,
      /* 更新角色数据存储 */
      editRouterFrom: {},
      /* 修改角色的表单身份校验 */
      editRouterFromRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      /* 控制分配权限对话框 */
      setRightDialogVisible: false,
      /* 所有权限数据 */
      rightsList: [],
      /* 树形控件的属性绑定对象   */
      treeProps: {
        /* 树型结构中显示的数据 */
        label: 'authName',
        /* 每一级嵌套的是什么属性 */
        children: 'children'
      },
      /* 默认选中的节点Id值数组 */
      defKeys: [],
      // 当前即将分配权限的id
      roleId: ''
    }
  },
  methods: {
    /* 获取所有角色的权限 */
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      // console.log('获取角色数据')
      this.rolesList = res.data
    },
    /* 显示添加角色的对话框 */
    showAddRouter () {
      this.isAddRouterDialog = true
    },
    /* 重置添加角色的表单 */
    resetRouterFrom () {
      this.$refs.addRouterFromRef.resetFields()
    },
    /* 添加角色 */
    addRouter () {
      /* 判断是否通过表单校验 */
      this.$refs.addRouterFromRef.validate(async valid => {
        if (!valid) return
        /* 判断添加的接口是否返回成功 */
        const { data: res } = await this.$http.post('/roles', this.addRouterFrom)
        if (res.meta.status !== 201) return this.$message.error('添加角色失败')
        /* 属性数据和页面 */
        this.getRolesList()
        /* 关闭对话框 */
        this.isAddRouterDialog = false
        /* 提示用户 */
        this.$message.success('添加角色成功')
      })
    },
    /* 显示修改角色对话框 */
    /* 根据id查询用户信息 */
    async showEidtRouter (routerId) {
    /* 根据id查询用户信息 */
    /* 根据id查询用户信息 */
      const { data: res } = await this.$http.get(`roles/${routerId}`)
      if (res.meta.status !== 200) return this.$message.error('查询角色信息失败')
      // 将查询到的信息存储到data中
      this.editRouterFrom = res.data
      /* 显示修改角色对话框 */
      this.isEidtRouterDialog = true
    },
    /* 修改角色对话框关闭事件 */
    editRouterColsed () {
      // 重置表单数据
      this.$refs.editRouterRef.resetFields()
    },
    /* 更新角色信息 */
    editRouter () {
      // 判断身份校验
      this.$refs.editRouterRef.validate(async valId => {
        /* 判断身份校验成功 */
        if (!valId) return this.$message.error('更新角色失败')
        /* 更新数据 */
        const { data: res } = await this.$http.put(`roles/${this.editRouterFrom.roleId}`, {
          roleName: this.editRouterFrom.roleName,
          roleDesc: this.editRouterFrom.roleDesc
        })
        if (res.meta.status !== 200) return this.$message.error('更新角色失败')
        /* 更新页面数据 */
        this.getRolesList()
        /* 提示用户 */
        this.$message.success('更新角色成功')
        /* 关闭对话框 */
        this.isEidtRouterDialog = false
      })
    },
    /* 通过id删除角色 */
    async showDeleteById (routerId) {
      // 显示提示框
      const result = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => { console.log(err) })
      if (result !== 'confirm') return this.$message.info('成功取消删除')
      /* 调接口请求 */
      const { data: res } = await this.$http.delete(`roles/${routerId}`)
      if (res.meta.status !== 200) return this.$message.info('删除失败')
      /* 关闭对话框 */
      /* 刷新数据页面 */
      this.getRolesList()
      /* 删除成功或者失败返回提示 */
      this.$message.success('删除成功')
    },
    /* 根据id删除对应的权限 */
    async  removeRightById (row, routerId) {
      /* 弹框提示用户是否删除 */
      const confirmResult = await this.$confirm('此操作将永久删除权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') return this.$message.info('取消删除权限')
      const { data: res } = await this.$http.delete(`roles/${row.id}/rights/${routerId}`)
      if (res.meta.status !== 200) return this.$message.error('权限删除失败')
      /* 刷新数据列表 */
      // this.getRolesList()
      /* 浅拷贝 */
      row.children = res.data
    },
    /* 展示分配权限的对话框 */
    async showSetRightDialog (row) {
      this.roleId = row.id
      /* 获取所有权限的数据 */
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限信息失败')
      /* 获取到的权限数据 保存到data中 */
      this.rightsList = res.data
      // console.log(this.rightsList)
      // 递归获取三级节点的id
      this.getLeafKeys(row, this.defKeys)
      this.setRightDialogVisible = true
    },
    /* 通过递归的形式,获取角色下三级权限的id 并且保存到defKeys中 */
    getLeafKeys (node, arr) {
      /* 判断是否是一个三级节点 */
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
      // return this.getLeafKeys(node.children, arr)
    },
    /* 监听分配权限对话框的事件 */
    setRightDialogColosed () {
      this.defKeys = []
    },
    /* 为角色分配权限 */
    async allotRights () {
      const keys = [
      //   /* 获取已经选中节点的数据 */
        ...this.$refs.treeRef.getCheckedKeys(),
        //   /* 获取半选中节点的数据 */
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) return this.$message.error('分配权限失败')
      // 提示信息
      this.$message.success('分配权限成功')
      /* 刷新数据 让页面响应式改变 */
      this.getRolesList()
      /* 隐藏对话框 */
      this.setRightDialogVisible = false
    }

  },
  created () {
    this.getRolesList()
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.dbttop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
